package com.mabs.util;

import java.sql.*;

/**JDBC模板工具类*/
public class JDBCTemplate {
	/**
	 * 执行非select语句的模板方法
	 */
	public static final int update(PreparedStatementCreator creator) {
		Connection conn = null;
		PreparedStatement pst = null;
		int result = -1;
		try {
			//conn = JdbcUtil.getConnection();
			//使用连接池获取连接
			conn = DbcpDataSource.getDataSource().getConnection();
			conn.setAutoCommit(false);
			pst = creator.create(conn);
			result = pst.executeUpdate();
			conn.commit();
		} catch (Exception e) {
			if (conn != null) {
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		} finally {
			DbcpDataSource.getDataSource().close(conn, pst);
		}
		return result;
	}

	/**
	 * 执行查询语句的模板方法
	 */
	public static final Object query(PreparedStatementCreator psc, ResultSetExtractor rse) {
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		Object obj = null;
		try {
			conn = DbcpDataSource.getDataSource().getConnection();
			conn.setAutoCommit(false);
			pst = psc.create(conn);
			rs = pst.executeQuery();
			obj = rse.extractor(rs);
			conn.commit();
		} catch (Exception e) {
			if (conn != null) {
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		} finally {
			DbcpDataSource.getDataSource().close(conn, pst, rs);
		}
		return obj;
	}
}
